import React, { useState, useEffect, useMemo } from "react";
import ScrollTypeSelector from "@/components/ScrollTypeSelector";
import {
  Modal,
  Input,
  Table,
  Pagination,
  Button,
  Tooltip,
  message,
  Select,
  Tag,
} from "antd";
import { DigitalEmployeelogs, logsClose } from "@/api/Home/home";
import { usetypesListtotalStore } from "@/store/leftcard";
import dayjs from "dayjs";

interface Props {
  open: boolean;
  onClose: () => void;
}

const ExceptionDialog: React.FC<Props> = ({ open, onClose }) => {
  const [selectedType, setSelectedType] = useState("全部");
  const [statusFilter, setStatusFilter] = useState<any>(""); // ""=全部, 0=未关闭, 1=已关闭
  const [searchText, setSearchText] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [data, setData] = useState<any[]>([]);
  const [columns, setColumns] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const pageSize = 5;

  const { typesList } = usetypesListtotalStore();

  useEffect(() => {
    if (open) {
      fetchLogs();
    }
  }, [open, selectedType, statusFilter, currentPage, searchText]);

  const allTypesList = useMemo(() => {
    if (!typesList) return [];
    return [{ name: "全部", total: 0, active: 0 }, ...typesList];
  }, [typesList]);

  useEffect(() => {
    if (allTypesList.length > 0) {
      setSelectedType(allTypesList[0].name);
    }
  }, [allTypesList]);

  const fetchLogs = async () => {
    try {
      const params: any = {
        logStatus: statusFilter,
        name: searchText,
        Page: currentPage,
        PageSize: pageSize,
      };

      if (selectedType !== "全部") {
        params.workflow = selectedType;
      }

      const res = await DigitalEmployeelogs(params);

      if (res.code === 1) {
        const { results, count } = res.data;
        const { fields } = res;

        const dynamicCols = Object.keys(fields).map((key) => {
          let renderFn = (value: any) => (
            <Tooltip placement="topLeft" title={value}>
              {value}
            </Tooltip>
          );

          if (key === "creatTime") {
            renderFn = (value: string) => (
              <Tooltip placement="topLeft" title={value}>
                {value ? dayjs(value).format("YYYY-MM-DD HH:mm:ss") : "-"}
              </Tooltip>
            );
          }

          if (key === "logStatus") {
            renderFn = (value: number) => (
              <Tag color={value === 0 ? "red" : "green"}>
                {value === 0 ? "未关闭" : "已关闭"}
              </Tag>
              // <Tooltip
              //   placement="topLeft"
              //   title={value === 0 ? "未关闭" : "已关闭"}
              // >
              //   {value === 0 ? "未关闭" : "已关闭"}
              // </Tooltip>
            );
          }

          return {
            title: fields[key],
            dataIndex: key,
            key: key,
            width: 100,
            ellipsis: { showTitle: false },
            render: renderFn,
          };
        });

        dynamicCols.push({
          title: "操作",
          key: "action",
          width: 120,
          fixed: "right",
          render: (_: any, record: any) => (
            <div className="flex gap-2">
              {record.status === 0 ? (
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleCloseLogs([record.id])}
                >
                  关闭
                </Button>
              ) : (
                <Tooltip title="该日志已关闭">
                  <Button size="small" disabled>
                    已关闭
                  </Button>
                </Tooltip>
              )}
            </div>
          ),
        });

        setColumns(dynamicCols);
        setData(results);
        setTotal(count);
      }
    } catch (error) {
      console.error(error);
    }
  };

  // 关闭日志
  const handleCloseLogs = async (ids: any[]) => {
    try {
      const res = await logsClose({ id: ids });
      if (res.code === 1) {
        message.success("关闭成功");
        fetchLogs();
      } else {
        message.error(res.message || "关闭失败");
      }
    } catch (err) {
      console.error(err);
      message.error("请求失败");
    }
  };

  return (
    <Modal
      title="异常记录"
      open={open}
      onCancel={onClose}
      footer={null}
      width={"85%"}
      maskClosable={false}
    >
      <ScrollTypeSelector
        typesList={allTypesList}
        selectedType={selectedType}
        onTypeChange={(item) => {
          setSelectedType(item.name);
          setCurrentPage(1);
        }}
        showCount={false}
      />

      <div className="flex items-center gap-3 mb-4">
        数字员工：
        <Input.Search
          placeholder="数字员工"
          allowClear
          onSearch={(value) => {
            setSearchText(value);
            setCurrentPage(1);
          }}
          style={{ width: 250 }}
        />
        日志状态：
        <Select
          value={statusFilter}
          style={{ width: 120 }}
          onChange={(val) => {
            setStatusFilter(val);
            setCurrentPage(1);
          }}
          options={[
            { value: "", label: "全部" },
            { value: 0, label: "未关闭" },
            { value: 1, label: "已关闭" },
          ]}
        />
      </div>

      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        pagination={false}
        size="middle"
        scroll={{ x: "max-content" }}
        locale={{
          emptyText: <div className="text-gray-500 py-6">暂无数据</div>,
        }}
      />

      <div className="mt-4 flex justify-end">
        <Pagination
          current={currentPage}
          pageSize={pageSize}
          total={total}
          showTotal={(total) => `共 ${total} 条`}
          onChange={(page) => setCurrentPage(page)}
          showSizeChanger={false}
        />
      </div>
    </Modal>
  );
};

export default ExceptionDialog;
